package service

import org.paic.d.D

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import java.text.SimpleDateFormat

// 打卡服务
class CardService {
	static Logger log = LoggerFactory.getLogger(CardService.class)

	public static final String urlHost = 'http://dy126.net'

	// 查询刷卡记录
	public static final String urlUserScanQuery = urlHost + '/wx/user-scan-query'
	// 显示刷卡按钮的页面
	public static final String urlUserScan = urlHost + '/wx/user-scan'
	// 刷卡的url
	public static final String urlSwipeCard = urlHost + '/wx/card-swipe'

	// 管理者
	public static final String urlUserManage = urlHost + '/ibid/index'

	// TODO
	/*
	回复“?”显示帮助提示；
	回复“me”显示个人信息；
	回复“list 距离今天的天数”显示个人打卡记录；
	回复“set 自己的名字”设置自己的姓名；
	回复“join 公司ID数字”加入一个公司；
	回复“create 公司名称”新建一个公司服务；
	*/
	static String getHelpContent(String openid){
		def user = UserService.getUserAsManager(openid)

		String c

		if(user){
		c = """
1. <a href="${urlUserScan}?openid=${openid}">我要打卡</a>


2. <a href="${urlUserScanQuery}?openid=${openid}">查询打卡记录</a>


3. <a href="${urlUserManage}?openid=${openid}&companyId=${user.companyId}&pwd=${user.pwd}">管理我的企业打卡信息</a>
		"""
		}else{
		c = """
1. <a href="${urlUserScan}?openid=${openid}">我要打卡</a>


2. <a href="${urlUserScanQuery}?openid=${openid}">查询打卡记录</a>
		"""
		}

		c
	}

	// 获取用户的最后一次打卡信息
	static Map getUserStat(String openid){
		def user = UserService.getUserWithCompany(openid)
		if(!user)
			return [:]

		def dao = D.gen()
		def record = dao.queryMap('select dd from T_IBID_CARD_RECORD where openid = ? order by id desc limit 1', 
			[openid])
		if(record){
			user.lastSwipeTime = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').format(record.dd)
		}else{
			user.lastSwipeTime = ''
		}

		user
	}

	// 添加一个刷卡器
	static int addScaner(int companyId, String name){
		def dao = D.gen()
		dao.add([companyId: companyId, name: name], 'T_IBID_CARD_SCANER')
	}

	// 获取所有有效打卡器，用于生成二维码
	static List getScanerIdList(){
		def dao = D.gen()
		dao.query('select id from T_IBID_CARD_SCANER where status = 1')
	}

	// 获取一个公司的打卡器列表
	static List getScanerListByCompanyId(int companyId){
		def dao = D.gen()
		dao.query('select id, name, type, begin_time, end_time from T_IBID_CARD_SCANER where status = 1 and company_id = ?', 
			[companyId])
	}

	// 显示打卡器信息，包括公司名称
	static Map getScanerName(int scanerId){
		def dao = D.gen()
		def item = dao.queryMap('''
			select a.*, b.name as company_name from 
				(select * from T_IBID_CARD_SCANER where id = ? and status = 1) a left join 
				T_IBID_CARD_company b on a.company_id = b.id
		'''
		, [scanerId])

		item
	}

	// 修改一个刷卡器的token，每分钟都刷新的
	static void updateScanerToken(int id, String token){
		def dao = D.gen()
		dao.update([id: id, token: token], 'T_IBID_CARD_SCANER', null)
	}

	// 会议实效
	static boolean isScanerMeetingValid(int scanerId){
		def dao = D.gen()
		def scaner = dao.queryMap('select * from T_IBID_CARD_SCANER where id = ? and status = 1', 
			[scanerId])

		if(!scaner)
			return false

		if('meeting' != scaner.type)
			return true

		long now = System.currentTimeMillis()
		if(scaner.beginTime){
			long beforeMillis = scaner.beforeMillis ?: 0
			// 签到早了
			if(now < scaner.beginTime.time - beforeMillis)
				return false 
		}
		if(scaner.endTime){
			long afterMillis = scaner.afterMillis ?: 0
			// 签到晚了
			if(now > scaner.endTime.time + afterMillis)
				return false 
		}

		true
	}

	// 用户刷卡时候，打卡器的信息校验
	static String isScanerValid(int scanerId, String token){
		def dao = D.gen()

		def scaner = dao.queryMap('select token, status from T_IBID_CARD_SCANER where id = ? and status = 1', 
			[scanerId])
		if(!scaner){
			log.warn('scaner-not-exists/invalid - ' + scanerId)
			return 'scaner-not-exists'
		}

		if(scaner.token != token){
			log.warn('scaner-token-not-match - ' + token + ' - ' + scaner.token)
			return 'scaner-token-not-match'			
		}

		return null
	}

	// 记录打卡信息
	static Date addRecord(int scanerId, String openid, double gx, double gy){
		def dd = new Date()

		def dao = D.gen()
		dao.add([scanerId: scanerId, openid: openid, gx: gx, gy: gy, dd: dd], 'T_IBID_CARD_RECORD')

		dd
	}

	// 查询打卡记录
	/*
	dd
	scaner_name
	*/
	static List getUserRecordList(String openid, String date, String dateEnd){
		def dao = D.gen()
		dao.query('''
			select a.dd, b.name as scaner_name from 
				(select scaner_id, dd from T_IBID_CARD_RECORD 
					where openid = ? and dd >= ? and dd < ? order by id desc) a left join 
				T_IBID_CARD_SCANER b on b.id = a.scaner_id
		'''
		, [openid, date, dateEnd])
	}

	// 查询公司的打卡记录
	/*
	openid
	dd
	scaner_name
	user_name
	*/
	static List getCompanyRecordList(int companyId, String date, String dateEnd, int scanerId){
		def dao = D.gen()

		String inner = scanerId != 0 ? 'and scaner_id = ?' : ''
		List args = scanerId != 0  ? [companyId, scanerId, date, dateEnd] : [companyId, date, dateEnd]
		dao.query("""
			select a.openid, a.dd, b.name as scaner_name, c.name as user_name from 
				(select scaner_id, openid, dd from T_IBID_CARD_RECORD 
					where scaner_id in 
						(select id from T_IBID_CARD_SCANER where company_id = ?) ${inner} and dd >= ? and dd < ? order by id desc) a left join 
				T_IBID_CARD_SCANER b on b.id = a.scaner_id left join 
				T_IBID_CARD_USER c on c.openid = a.openid
		"""
		, args)
	}
}
